<template>
  <div class="equipmentMoveDetails h100">
    <editPageNew
      ref="editPage"
      :rightBtnArr="rightBtnArr"
      :stepConfig="stepConfig"
      showStep
      showTopTitle
      :creatInfo="formData"
    >
      <template slot="editPageTitle">
        <i class="el-icon-document TitleImg"></i>
        设备异动 {{formData.code}}
      </template>
      <div class="orderTitle">
        <div class="tipText">标题规则：设备管理单位+"异动申请"</div>
        <div v-show="!showInput" class="name">
          <span style="color: red"></span>
          <span  class="titleText" :title="orderTitle">{{ orderTitle }}</span>
          <el-link
            v-show="!baseAttachBtn"
            style="font-size: 20px"
            icon="el-icon-edit-outline"
            @click="editTitle"
          ></el-link>
        </div>
        <div v-show="showInput" class="name-input">
          <el-input
            type="text"
            v-model="orderTitle"
            @blur="loseFocus"
            @change="userInputTitle"
            placeholder="请输入名称"
            clearable
            ref="mark"
          >
            <template slot="prepend" style="color: red">标题</template>
          </el-input>
        </div>
      </div>
      <el-collapse v-model="activeNames">
        <el-collapse-item name="1">
          <template slot="title">基本信息</template>
          <editForm :formConfig="basicConfig" ref="basicForm" :formData="formData">
            <template v-slot:inputToolSlot>
              <el-button
                size="mini"
                type=""
                icon="el-icon-circle-plus-outline"
                @click="openPopup('', 'add')"
                class="btn-text-blue"
                :disabled="false"
              >新增</el-button>
            </template>
          </editForm>
          <!-- 非公共的表格 -->
          <div class="line">
            <div class="lable">参数修改明细:</div>
            <div class="linTable" v-loading="loading">
              <!-- 非公共的表格 -->
              <editTableNew
                @handleClickAdd="addParameter"
                :tableSetting="deviceSeting"
                :tableData="parameterListSorted"
                :hideBtn="hideBtn"
                :showOperate="showOperate"
                ref="addDetails"
              ></editTableNew>
            </div>
          </div>
          <div class="attachConten">
            <div class="attachTitle">附件:</div>
            <div class="tebleDiv">
              <attachFormNew
                style="width: 60%"
                :disabled="hideBtn"
                :attachSetting="attachSetting"
                isDelete
                multiple
                ref="attachForm"
              ></attachFormNew>
            </div>
          </div>
        </el-collapse-item>
        <div class="record__workflow" v-if="showFlow">
          <el-collapse-item name="2">
            <template slot="title">工作流</template>
            <workFlow
              v-if="showFlow"
              ref="workFlow"
              :isDetails="pageType == 'query'"
              :currentFlowData="formData"
              @submitSuccess="workFlowSuccess"
              workflowCode="equipment_change"
            ></workFlow>
          </el-collapse-item>
        </div>
      </el-collapse>
    </editPageNew>
    <dialogPublic
      :title="'审核信息'"
      :show.sync="showFlowDialog"
      noFootBtn
      appendTobody
      fullscreen
      @doClose="() => (showFlowDialog = false)"
    >
      <workFlow
        v-if="showFlowDialog"
        :isDetails="pageType == 'query'"
        :currentFlowData="formData"
        @submitSuccess="workFlowSuccess"
        workflowCode="equipment_change"
      ></workFlow>
    </dialogPublic>
    <dialogPublic
      title="设备台账"
      v-if="showEquipmentPopup"
      :show.sync="showEquipmentPopup"
      @doSubmit="confirmEquipmentMoveChange"
      @doClose="()=>(showEquipmentPopup = false)"
      :fullscreen="true"
      :noFootBtn="isNoFoot"
    >
      <equipmentManagePopup ref="equipMovePopup" :popupType="popupType" :parameterList="parameterList" :defaultNodeId="defaultNodeId" @handleClickTree="handleClickTree" @getChangeEquipmentMoveParams="getChangeEquipmentMoveParams" @getTreeId="getTreeId"></equipmentManagePopup>
    </dialogPublic>
  </div>
</template>
<script>
import {
  insertApi, //新增
  getDetailsApi, //获取详情
  deleteApi,
  getBatchGenericParams
} from "@/api/equipmentLedger/equipmentMove";
import {
  getEquipment, //获取设备参数
  getParamByIdApi,
  getLeftUpperApi
} from "@/api/equipmentLedger/equipmentManage";
import {
  getPresetParamsApi //获取设备参数
} from "@/api/common";
import editTableNew from "../editTableNew";
import equipmentManagePopup from '@/views/equipmentLedger/equipmentMove/equipmentPopup/equipmentManagePopup'
export default {
  components: { editTableNew, equipmentManagePopup },
  provide() {
    return {
      updateOldEquipmentMoveParams: this.updateOldEquipmentMoveParams,
      getPreviousParams: this.getPreviousParams,
      getHideRepeatNode: () => {
        return this.hideRepeatNode
      },
      getSelectedNodeList: () => {
        return this.selectedNodeList
      }
    }
  },
  data() {
    return {
      hideRepeatNode: true,
      popupType: '',
      defaultNodeId: '', // 默认选中的设备节点
      equipmentId: 0, // 选中设备的id
      equipmentName: '', // 设备名称
      showEquipmentPopup: false, // 设备台账弹窗
      activeNames: ["1", "2"],
      creatInfo: {},
      hideBtn: false,
      showFlowDialog: false,
      isChangeRouter: false,
      showInput: false,
      userInput: false,
      loading: false,
      orderTitle: "",
      pageType: "",
      currentEquipDeptName: "",
      equipmentList: [],
      equipObj: [],
      parameterList: [],
      tempTableData: [], //临时设备参数表格数据
      moveData: {},
      isNoFoot: false,
      // 首次进入详情页
      firstEnter: true,
      basicConfig: {
        itemArr: [
          {
            type: "text", //device\deviceClassify
            label: "设备名称",
            prop: "equipmentName",
            placeholder: "新增明细后自动回填",
            // required: true,
            // disabled: true, // 禁用
            hasInputAppend: true // input右侧是否有自定义按钮
          },
          {
            label: "设备管理单位",
            prop: "equipDeptName",
            propArr: "equipDeptArr",
            idsStr: "equipDeptId",
            option: [],
            multiple: false, //是否多选
            allowCreate: false, //是否允许创建条目
            isOutOrg: 0, //是否事外单位
            level: "3", //组织层级筛选 2.部门 3.单位
            type: "dept-select",
            trigger: "change",
            methods: obj => {
              this.currentEquipDeptName = obj[0].name || "";
            },
            required: true,
            span: 8
          },
          {
            label: "异动原因",
            prop: "reason",
            type: "textarea",
            maxlength: "300",
            required: true,
            span: 24,
            rows: 5
          },
          {
            label: "异动内容",
            prop: "content",
            type: "textarea",
            maxlength: "300",
            required: true,
            span: 24,
            rows: 5,
            isHide: true
          }
        ]
      },
      showOperate: true,
      //设备参数表格
      deviceSeting: {
        title: "",
        select: false,
        addMethons: true,
        maxHeight: 400,
        data: [],
        btnArr: [],
        deleteMethods: (row, data) => {},
        column: [
          {
            label: "设备名称",
            prop: "equipName",
            id: "equipId",
            type: "disableText",
          },
          {
            label: "异动参数",
            prop: "paramName",
            id: "paramId",
            type: "disableText",
          },
          {
            label: "改前值",
            prop: "paramOld",
            type: "disableText",
            disabled: true
          },
          {
            label: "改后值",
            prop: "paramNewValue",
            idsStr: "paramNewResult",
            type: "disableText",
            disabled: true
          }
        ],
        buttonArr: [
          {
            name: "编辑",
            isShow: row => {
              let { status } = this.$route.query;
              return status == null || status < 2;
            },
            methods: (row, index) => {
              console.log(row, index)
              this.openPopup(row.equipId, 'edit')
              // this.deleteRow(row, index);
            }
          },
          {
            name: "删除",
            isShow: row => {
              let { status } = this.$route.query;
              return status == null || status < 2;
            },
            methods: (row, index) => {
              this.deleteRow(row, index);
            }
          },
          {
            name: "查看",
            isShow: row => {
              let { status } = this.$route.query;
              return status == 2;
            },
            methods: (row, index) => {
              console.log(row, index)
              this.openPopup(row.equipId, 'view')
              // this.deleteRow(row, index);
            }
          }
        ]
      },
      //附件设置
      attachSetting: {
        businessId: "", //单据的ID
        businessType: "base"
      },
      status: "",
      formData: {},
      statusArr: ["0", "1", "2"],
      previousParams: {},
      selectedNodeList: [],
      repeatMap: {}
    };
  },
  computed: {
    // 排序后的参数列表
    parameterListSorted() {
      const list = [...this.parameterList]
      list.sort((a, b) => {
        // name排序
        if(a.equipName < b.equipName) return -1
        if(a.equipName > b.equipName) return 1
        return 0
      })
      return (list.length > 0 && list) || []
    },
    rightBtnArr() {
      let arr = [
        {
          text: "保存",
          icon: "el-icon-check",
          hide:
            ["query", "perform"].includes(this.pageType) ||
            ["1", "2"].includes(this.formData.status),
          content: this.$store.getters["isBtnAuth"]("edit")
            ? null
            : "未授权此功能！",
          disabled: !this.$store.getters["isBtnAuth"]("edit"),
          methods: () => {
            this.doSubmit("0");
          }
        },
        {
          text: "提交",
          icon: "el-icon-position",
          hide:
            ["perform", "query"].includes(this.pageType) ||
            ["1", "2"].includes(this.formData.status),
          content: this.$store.getters["isBtnAuth"]("edit")
            ? null
            : "未授权此功能！",
          disabled: !this.$store.getters["isBtnAuth"]("edit"),
          methods: () => {
            this.doSubmit("1");
          }
        },
        {
          text: "删除",
          icon: "el-icon-position",
          hide:
            ["perform", "query"].includes(this.pageType) ||
            ["1", "2"].includes(this.formData.status),
          content: this.$store.getters["isBtnAuth"]("delete")
            ? null
            : "未授权此功能！",
          disabled: !this.$store.getters["isBtnAuth"]("delete"),
          methods: () => {
            this.deleteData();
          }
        }
      ];
      return arr;
    },
    stepConfig() {
      let step = this.statusArr.indexOf(this.status);
      let obj = {
        nowStep: parseInt(step), //当前步骤，对应stepItem数组的下标，例如：0-步骤一、1-步骤二
        stepItem: ["草稿", "待审核", "已完成"]
      };
      return obj;
    },
    showFlow() {
      return ["1", "2"].includes(this.formData.status);
    },
    baseAttachBtn() {
      if (this.status == "0" || this.status == undefined) {
        return false;
      } else {
        return true;
      }
    }
  },
  watch: {
    status: {
      handler(val) {
        this.formData.status = val;
        this.initPage();
        switch (val) {
          case "0":
            this.activeNames = ["1"];
            break;
          case "1":
            this.activeNames = ["2"];
            break;
          default:
            this.activeNames = ["1", "2"];
            break;
        }
      }
    },
    currentEquipDeptName: {
      handler(val) {
        if (!this.userInput) {
          this.orderTitle = val + "异动申请";
        }
      }
    },
    parameterList(newVal) {
      const selectedMap = new Map()
      newVal.forEach((item) => {
        selectedMap.set(item.equipId, item)
      })
      this.selectedNodeList = Array.from(selectedMap.values())
      // 设备名称回显
      const equipNameStr = this.selectedNodeList.map(item => item.equipName).join(',')
      this.$refs.basicForm.setFormItem("equipmentName", equipNameStr);
    }
  },
  created() {
    this.init();
  },
  mounted() {},
  methods: {
    init() {
      let { pageType, status, id } = this.$route.query;
      this.pageType = pageType;
      if(status == 2) this.isNoFoot = true
      if (id) {
        let haveJurisdiction = this.$store.getters["isBtnAuth"]("edit");
        this.pageType = haveJurisdiction ? "edit" : "details";
        this.formData.id = id;
        this.getDetails();
      } else {
        this.showInput = true;
      }
    },
    handleClickTree(node) {
      if(this.equipmentList.findIndex(item => item.equipId === node.id) >= 0) {
        this.isNoFoot = true
      } else {
        this.isNoFoot = false
      }
      if(!this.hideRepeatNode) {
        this.isNoFoot = (node.id == this.defaultNodeId && this.popupType !== 'view') ? false : true
      }
    },
    // 打开弹窗
    async openPopup(id = '', type = '') {
      if(!id) {
        id = this.$store.getters.currentInfo.currOrg
        await getLeftUpperApi({orgId: id}).then((res) => {
          if (res.data) {
            this.defaultNodeId = res.data.id
          }
        });
      } else {
        this.defaultNodeId = id
      }
      if(type) this.popupType = type
      if(type == 'add') this.hideRepeatNode = true
      if(type == 'edit') this.hideRepeatNode = false
      this.showEquipmentPopup = true
    },
    async confirmEquipmentMoveChange() {
      this.$refs.equipMovePopup.getCurrentTreeNode()
      await this.$refs.equipMovePopup.$refs.eBasicInfo.getAfterChangeEquipmentMoveParams()
      this.showEquipmentPopup = false
    },
    updateOldEquipmentMoveParams(data) {
      this.previousParams = data
    },
    getPreviousParams() {
      return this.previousParams
    },
    getChangeEquipmentMoveParams(data) {
      let { id } = this.$route.query;
      let index = 0
      // 更改后的基本信息、技术参数两个对象合并(他们的key是唯一的，合并不会冲突)
      let newEquipmentMoveParams = Object.assign({}, data.paramsData, data.entData)
      // 更改前的参数值
      let { oldEquipmentMoveParams } = data
      let paramList = []
      for (const key in newEquipmentMoveParams) {
        if (Object.hasOwnProperty.call(newEquipmentMoveParams, key)) {
          const newValue = newEquipmentMoveParams[key];
          if(oldEquipmentMoveParams[key] && oldEquipmentMoveParams[key].paramValue !== newValue) {
            const paramNewResult = typeof newEquipmentMoveParams[key + 'Id'] === 'string' ? newEquipmentMoveParams[key + 'Id'] : newEquipmentMoveParams[key + 'Id'] == null ? '' : newEquipmentMoveParams[key + 'Id'].join(',')
            paramList.push({
              changeId: id,
              editable: true,
              equipId: this.equipmentId,
              equipName: this.equipmentName,
              paramId: oldEquipmentMoveParams[key].paramId,
              paramName: oldEquipmentMoveParams[key].paramName,
              paramNewResult: paramNewResult,
              paramNewValue: newEquipmentMoveParams[key],
              paramOld: oldEquipmentMoveParams[key].paramValue,
              rowIndex: index + 1,
            })
          } else if (oldEquipmentMoveParams[key] && oldEquipmentMoveParams[key].paramValue === newValue) {
            const index = this.parameterList.findIndex((i) => {
              return this.equipmentId === i.equipId && oldEquipmentMoveParams[key].paramValue === newValue
            })
            if (index > -1) {
              this.parameterList.splice(index, 1)
            }
          }
        }
      }
      // 合并后的对象
      let mergeParamList = []
      const map = new Map()

      this.parameterList.forEach(item => {
        const key = `${item.equipId}-${item.paramId}`
        map.set(key, item)
      })
      paramList.forEach(item => {
        const key = `${item.equipId}-${item.paramId}`
        if(map.has(key)) {
          // equipId、paramId 均存在，只需要更新值
          const existItem = map.get(key)
          map.set(key, {...existItem, ...item})
        } else {
          map.set(key, item)
        }
      })

      mergeParamList = Array.from(map.values())
      this.parameterList = mergeParamList

      this.parameterList.forEach(item => {
        if(!this.repeatMap[item.equipId]) {
          this.equipmentList.push({
            equipId: item.equipId,
            equipName: item.equipName,
            label: item.equipName,
            value: item.equipId
          })
          this.repeatMap[item.equipId] = true
        }
      })
    },
    getTreeId(data) {
      this.equipmentId = data.equipId
      this.equipmentName = data.equipName
      const form = {
        equipmentId: data.equipId
      }
      // 设备名称回显
      // this.$refs.basicForm.setFormItem("equipmentName", data.equipName);
      // const index = this.equipmentList.findIndex(i => {
      //   return i.id === data.value
      // })
      // if(index < 0) {
      //   this.equipmentList.push(data)
      // }
      // const equipNameStr = this.equipmentList.map(item => {
      //   return item.equipName
      // }).join(',')
      // this.$refs.basicForm.setFormItem("equipmentName", equipNameStr);

      // 带出设备管理单位
      this.setDeptManage(form)
    },
    initPage() {
      if (
        ["query", "details"].includes(this.pageType) ||
        ["1", "2"].includes(this.status)
      ) {
        let itemArr = [];
        //深度拷贝数组对象(可拷贝函数)
        $.extend(true, itemArr, this.basicConfig.itemArr);
        itemArr.map(i => (i.disabled = true));
        this.basicConfig.itemArr = itemArr;
        this.hideBtn = true;
      }
    },
    async getDetails() {
      let res = await getDetailsApi(this.formData.id);
      this.defaultNodeId = res.data.equipments[0].equipId
      this.loading = true;
      let data = res.data;
      this.status = res.data.status;
      this.attachSetting.businessId = res.data.id;

      this.initPage();
      /* 标题 */
      this.orderTitle = data.name;
      this.currentEquipDeptName = data.equipDeptName;
      if (
        data.name == data.equipDeptName + "设备异动" ||
        [null, ""].includes(data.name)
      ) {
        //用户是否自定义了工单名
        this.userInput = false;
        if ([null, ""].includes(data.name)) {
          this.orderTitle = data.deptManageName + "设备异动";
        }
      } else {
        this.userInput = true;
      }
      /* 设备 */
      let equipList = data.equipments || [];
      let equipNameArr = [];
      let equipNameId = [];
      equipList.map(i => {
        i.value = i.equipId;
        i.label = i.equipName;
        equipNameArr.push(i.equipName);
        equipNameId.push(i.equipId);
      });
      data.equipmentId = equipNameId.toString();
      this.equipmentList = equipList;
      //判断是否是主要设备
      this.judgeMainEquipment(equipNameId);
      if (this.$refs.addDetails) {
        this.$refs.addDetails.setColumnOption("equipName", this.equipmentList);
      }

      /* 设备管理单位 */
      let { equipDeptName, equipDeptId } = data;
      data.equipDeptArr = data.equipDeptId;
      let option = this.$utils.getOptionData(equipDeptName, equipDeptId, "0");
      this.formData = data;

      setTimeout(() => {
        this.$refs.basicForm.setItemOption("equipDeptName", option);
      }, 200);

      /* 处理 参数表格数据 */
      let list = data.params || [];
      let selecctId = "";
      for (let i = 0; i < list.length; i++) {
        if (["0", undefined].includes(this.status)) {
          if (this.pageType != "details") {
            list[i].editable = true;
          }
          await this.getDeviceDetails(list[i].equipId, list[i]);
          let item = await this.getParamMethods(list[i].paramId);
          this.setEntityConfig(item, list[i]);
        }
      }
      this.parameterList = list;
      this.loading = false;

      let { deviceId } = this.$route.query;
      if (this.firstEnter && deviceId) {
        this.firstEnter = false;
        this.openPopup(deviceId, 'view');
      }
    },
    //根据参数ID查询参数详情
    async getParamMethods(id) {
      let res = await getParamByIdApi(id);
      return res.data;
    },
    //设备带出设备管理单位以及专业
    async setDeptManage(form) {
      let res = await getPresetParamsApi(form);
      let deptObj = res.data && res.data["0005000"] || {}; //设备管理单位“0005000”
      if (JSON.stringify(deptObj) == "{}") {
        this.$message.warning(
          "该设备没有设备管理单位，请选择有设备管理单位的设备！"
        );
        this.currentEquipDeptName = "";
        this.$refs.basicForm.setFormItem("equipDeptName", "");
        this.$refs.basicForm.setFormItem("equipDeptId", "");
        this.$refs.basicForm.setFormItem("equipDeptArr", "");
        this.$refs.basicForm.setItemOption("equipDeptName", []);
      } else {
        let { paramResult, paramValue } = deptObj;
        this.currentEquipDeptName = paramValue;
        let option = this.$utils.getOptionData(paramValue, paramResult, "0");
        this.$refs.basicForm.setItemOption("equipDeptName", option);
        setTimeout(() => {
          this.$refs.basicForm.setFormItem("equipDeptName", paramValue);
          this.$refs.basicForm.setFormItem("equipDeptId", paramResult);
          this.$refs.basicForm.setFormItem("equipDeptArr", paramResult);
        }, 200);
      }
    },
    //获取设备的参数
    async getDeviceDetails(id, row) {
      let res = await getEquipment(id);
      if (res.data) {
        let basic = res.data.basicParams || []; //基本参数
        let tech = res.data.techParams || []; //技术参数
        let basicOption = {
            label: "基本参数",
            options: []
          },
          techOption = {
            label: "技术参数",
            options: []
          };
        let option = [];
        basic.map(i => {
          i.label = i.paramName;
          i.value = i.paramId;
          basicOption.options.push(i);
        });
        option.push(basicOption);
        tech.map(i => {
          i.label = i.paramName;
          i.value = i.paramId;
          techOption.options.push(i);
        });
        option.push(techOption);
        row.rowOption = option;
      }
    },
    //点击新增修改的参数
    async addParameter() {
      this.parameterList = await this.$refs.addDetails.getTableData(false);
      console.log('addParameter', this.parameterList)
      if (this.equipmentList.length > 0) {
        //不校验必填参数，获取表格数据
        let obj = {
          equipName: "",
          equipId: "",
          paramId: "",
          paramName: "",
          paramNewValue: "",
          paramNewResult: "",
          paramOld: "",
          rowIndex: this.parameterList.length,
          editable: true,
          rowOption: []
        };
        this.parameterList.push(obj);
        // this.tempTableData = await this.$refs.addDetails.getTableData(false);
      } else {
        this.$message.warning("请先选择设备");
      }
    },
    //根据选择的设备，过滤参数表格里面的数据
    async setParameterTable() {
      let parameterList = await this.$refs.addDetails.getTableData(false);
      let equipId = [];
      this.equipmentList.map(i => {
        equipId.push(i.equipId);
      });
      let list = [];
      parameterList.map(i => {
        if (equipId.includes(i.equipId)) {
          list.push(i);
        }
      });
      this.$refs.addDetails.setTableData(list);
      this.parameterList = list;
    },
    async judgeMainEquipment(ids) {
      let res = await getBatchGenericParams(ids);
      let data = res.data || [];
      let notMainName = [];
      let main = [];
      ids.map(i => {
        if (data[i]) {
          let keyArr = Object.keys(data[i]) || [];
          if (keyArr.includes("0009000")) {
            main.push(i);
          } else {
            notMainName.push(i);
          }
        }
      });
      this.equipmentList.map(i => {
        if (notMainName.includes(i.value)) {
          //非主要设备
          i.disabled = true;
          i.content = "非主要设备，请联系台账管理员进行修改！";
        }
      });

      //设备参数修改明细-设备名称的选项值
      if (this.$refs.addDetails) {
        this.$refs.addDetails.setColumnOption("equipName", this.equipmentList);
      }
    },
    async doSubmit(type) {
      let data = await this.$refs.basicForm.getFormData();
      data.status = "0";
      let reData = await this.$refs.addDetails.getTableData();
      let tableEquip = [];
      reData.map((i, index) => {
        i.sort = index + 1;
        delete i.rowOption;
        delete i.option;
        delete i.inputType;
        if (!tableEquip.includes(i.equipId)) {
          tableEquip.push(i.equipId);
        }
      });
      data.params = reData;
      data.equipments = this.equipmentList;
      data.name = this.orderTitle;
      if (type == "1") {
        //提交时对设备进行校验
        if (this.equipmentList.length != tableEquip.length) {
          let equipList = [];
          this.equipmentList.map(i => {
            if (!tableEquip.includes(i.equipId)) {
              equipList.push(i.equipName);
            }
          });
          this.$message.warning(
            "含有未作变动设备：" +
              equipList.toString() +
              "！请删掉未变动的设备或补充相应设备的异动参数表，再提交！"
          );
        } else {
          this.$confirm(`提交后数据将会自动保存，是否继续`, "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          })
            .then(() => {
              this.submitData(data, type);
            })
            .catch(e => {});
        }
      } else {
        this.submitData(data, type);
      }
    },
    submitData(data, type) {
      //类型转换
      insertApi(data)
        .then(res => {
          this.$message.success("操作成功！");
          this.formData = res.data;
          this.$utils.updateStorage();
          if (this.pageType == "add") {
            this.pageType = "edit";
            this.formData = res.data;
            this.attachSetting.businessId = res.data.id;
            if (type == "1") {
              this.showFlowDialog = true;
              this.isChangeRouter = true;
            } else {
              this.changeRouter();
            }
          } else if (this.status == "0" && type == "1") {
            this.showFlowDialog = true;
          }
          this.getDetails();
          this.saveAttachFile();
        })
        .catch(e => {
          console.log(e);
        });
    },
    changeRouter() {
      /* 修改路由参数 */
      let obj = JSON.parse(JSON.stringify(this.$router.currentRoute.query));
      obj = Object.assign(obj, {
        id: this.formData.id,
        pageType: "edit"
      });
      this.$router.push({
        query: obj
      });
    },
    //工作流提交成功之后
    workFlowSuccess() {
      if (this.isChangeRouter) {
        this.isChangeRouter = false;
        this.changeRouter();
      }
      this.showFlowDialog = false;
      this.$utils.updateStorage();
      if (this.$refs.workFlow) {
        this.$refs.workFlow.getFlowInfo();
      }
      this.getDetails();
    },
    //设置实体类节点参数表单,以及参数的值
    setEntityConfig(value, rowData) {
      let inputType = this.changeType(value.enterType);
      let item = {
        label: value.paramName,
        prop: value.paramId,
        idsStr: value.paramId + "Id",
        type: inputType,
        required: value.must
      };
      if (["multi"].includes(value.enterType)) {
        //多选
        item.multiple = true;
      }
      if (["multi_man", "multi_org"].includes(value.enterType)) {
        item.multiple = true;
      }
      if (["radio", "select"].includes(inputType)) {
        item.prop = value.paramId + "Id";
        item.methods = (obj, data) => {
          data[value.paramId] = obj.label;
        };
        delete item.idsStr;
        if (value.dataText && value.dataText != "") {
          let option = $.parseJSON(value.dataText);
          item.option = option;
        } else {
          //没有选项值，用数据字典的值
          if (value.enterType == "brand") {
            //选厂商
            item.option = this.$store.getters["vendorList"];
          }
        }
      }
      rowData.inputType = inputType;
      rowData.option = item.option;
      this.$refs.addDetails.setColumn("paramNewValue", item);
    },
    //输入类型
    changeType(type) {
      let inputType = "";
      switch (type) {
        case "radio":
          inputType = "select";
          break; //单选
        case "multi":
          inputType = "select";
          break; //多选
        case "date_day":
          inputType = "date";
          break; //日期
        case "brand":
          inputType = "select";
          break; //厂商
        case "date_time":
          inputType = "datetime";
          break; //选日期时间
        case "box":
          inputType = "text";
          break; //文本框
        case "location":
          inputType = "location";
          break; //选位置
        case "radio_org":
          inputType = "dept";
          break; //组织单选
        case "multi_org":
          inputType = "dept";
          break; //选组织-多选
        case "radio_man":
          inputType = "user";
          break; //选人-单选
        case "multi_man":
          inputType = "user";
          break; //选人-多选
      }
      return inputType;
    },
    //用户输入工单标题
    userInputTitle(val) {
      if (["", null].includes(val) || val.match(/^[ ]*$/)) {
        this.userInput = false;
      } else {
        this.userInput = true;
      }
    },
    //失去焦点
    loseFocus() {
      if (
        ["", null].includes(this.orderTitle) ||
        this.orderTitle.match(/^[ ]*$/)
      ) {
        if (this.currentEquipDeptName) {
          this.$message.warning("标题不能为空，已为您自动生成标题！");
          this.orderTitle = this.currentEquipDeptName + "异动申请";
          this.showInput = false;
        } else {
          this.showInput = true;
        }
      } else {
        this.showInput = false;
      }
    },
    //编辑标题
    editTitle() {
      this.showInput = true;
      setTimeout(() => {
        this.$refs.mark.focus();
      }, 0);
    },
    //删除参数表格内的数据
    async deleteRow(row, index) {
      this.parameterList = await this.$refs.addDetails.getTableData(false);
      this.parameterList.splice(index, 1);
      this.parameterList.map((i, index) => {
        i.rowIndex = index;
      });
      this.equipmentList = this.equipmentList.filter(item => {
        return this.parameterList.some((param) => {
          return item.equipId === param.equipId
        })
      })
    },

    //删除
    deleteData() {
      //对数据来源进行判断
      this.$confirm(`是否确认删除`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          deleteApi(this.formData.id).then(res => {
            this.$utils.updateStorage();
            this.$message.success("操作成功");
            this.$refs.editPage.closePage(600);
          });
        })
        .catch(e => {});
    },
    //保存附件
    saveAttachFile() {
      this.$refs.attachForm.save();
    }
  }
};
</script>
<style lang="less" scoped>
.equipmentMoveDetails {
  background-color: #ffffff;
  .TitleImg {
    margin-right: 2px;
    font-size: 22px;
  }

  .orderTitle {
    height: 60px;
    margin: 0 0 10px 0;
    .tipText {
      color: #cecece;
      text-align: left;
    }
  .titleText {
    display: inline-block;
    height: 30px;
    max-width:800px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    margin-right: 5px;
  }
  .el-link{
    margin-bottom: 5px;
  }
    .name {
      font-size: 18px;
      padding: 0 10px;
      height: 40px;
      font-weight: bold;
      line-height: 40px;
      text-align: left;
      padding: 0 10px;
    }
    .name-input {
      width: 600px;
      height: 40px;
      line-height: 40px;
    }
    .remindColor {
      /deep/.el-input__inner {
        border: 1px solid red !important;
      }
    }
  }
  .line {
    display: flex;
    flex-flow: wrap nowrap;
    .lable {
      width: 135px;
      padding-left: 12px;
    }
    .linTable {
      width: calc(100% - 150px);
    }
  }
  .attachConten {
    margin-top: 15px;
    display: flex;
    flex-flow: wrap nowrap;
    .redPoint {
      color: red;
    }
    .attachTitle {
      width: 120px;
    }
    .tebleDiv {
      width: 100%;
    }
  }
}
</style>